﻿using System;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Isaac.Joy.Mvc.Web;
using UIShell.OSGi;
using UIShell.OSGi.Core.Service;
using UIShell.OSGi.Loader;

[assembly: PreApplicationStartMethod(typeof(MvcApplication), "BundleStart")]
namespace Isaac.Joy.Mvc.Web
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : HttpApplication
    {
        public static void BundleStart()
        {
            //BuildManager.AddReferencedAssembly(typeof(BundleRuntime).Assembly);
            
            var runtime = new BundleRuntime();
            runtime.Start();

            foreach (var bundle in runtime.Framework.Bundles)
            {
                var bundleData = runtime.GetFirstOrDefaultService<IBundleInstallerService>()
                                 .GetBundleDataByName(bundle.SymbolicName);
                if (bundleData == null) continue;

                var serviceContainer = runtime.Framework.ServiceContainer;
                var service = serviceContainer.GetFirstOrDefaultService<IRuntimeService>();
                var assemlbies = service.LoadBundleAssembly(bundle.SymbolicName);

                foreach (var assemlby in assemlbies)
                {
                    var shadowCopyPlugFolder = new DirectoryInfo(
                        Path.Combine(AppDomain.CurrentDomain.DynamicDirectory, bundle.SymbolicName));
                    if (!Directory.Exists(shadowCopyPlugFolder.FullName))
                        Directory.CreateDirectory(shadowCopyPlugFolder.FullName);

                    var assemlbyFile = new FileInfo(assemlby.Location);
                    var shadowCopiedPlug = new FileInfo(
                        Path.Combine(shadowCopyPlugFolder.FullName, assemlbyFile.Name));

                    File.Copy(assemlby.Location, shadowCopiedPlug.FullName, true);
                    BuildManager.AddReferencedAssembly(
                        Assembly.Load(AssemblyName.GetAssemblyName(shadowCopiedPlug.FullName)));
                }
            }
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            ControllerBuilder.Current.SetControllerFactory(new BundleRuntimeControllerFactory());
            ViewEngines.Engines.Add(new BundleRazorViewEngine());

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}